package com.ship.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.ship.common.core.constant.UserConstants;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.web.controller.BaseController;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.common.security.annotation.RequiresPermissions;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.system.domain.SysBindPerms;
import com.ship.system.domain.SysMenu;
import com.ship.system.domain.SysMenuData;
import com.ship.system.service.ISysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * 菜单信息
 *
 * @author zhangyh
 */
@RestController
@RequestMapping("/menu")
@Api(value = "sysMenu", tags = "菜单信息")
public class SysMenuController extends BaseController {
    @Autowired
    private ISysMenuService menuService;

    /**
     * 获取菜单列表
     */
    @ApiOperation(value = "获取菜单列表")
    @RequiresPermissions("system:menu:list")
    @GetMapping("/list")
    public JsonResult list(SysMenu menu) {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return JsonResult.success(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @ApiOperation(value = "根据菜单编号获取详细信息")
    @RequiresPermissions("system:menu:query")
    @GetMapping(value = "/{menuId}")
    public JsonResult getInfo(@PathVariable Long menuId) {
        return JsonResult.success(menuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @ApiOperation(value = "获取菜单下拉树列表")
    @GetMapping("/treeselect")
    public JsonResult treeselect(SysMenu menu) {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return JsonResult.success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @ApiOperation(value = "加载对应角色菜单列表树")
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public JsonResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(userId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        jsonObject.put("menus", menuService.buildMenuTreeSelect(menus));
        return JsonResult.success(jsonObject);
    }

    /**
     * 新增菜单
     */
    @ApiOperation(value = "新增菜单")
    @RequiresPermissions("system:menu:add")
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public JsonResult add(@Validated @RequestBody SysMenu menu) {
        if (!menuService.checkMenuNameUnique(menu)) {
            return JsonResult.failed("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return JsonResult.failed("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(SecurityUtils.getUsername());
        return JsonResult.success(menuService.insertMenu(menu));
    }

    /**
     * 修改菜单
     */
    @ApiOperation(value = "修改菜单")
    @RequiresPermissions("system:menu:edit")
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public JsonResult edit(@Validated @RequestBody SysMenu menu) {
        if (!menuService.checkMenuNameUnique(menu)) {
            return JsonResult.failed("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return JsonResult.failed("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            return JsonResult.failed("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());
        return JsonResult.success(menuService.updateMenu(menu));
    }

    /**
     * 删除菜单
     */
    @ApiOperation(value = "删除菜单")
    @RequiresPermissions("system:menu:remove")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public JsonResult remove(@PathVariable("menuId") Long menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            return JsonResult.failed("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId)) {
            return JsonResult.failed("菜单已分配,不允许删除");
        }
        return JsonResult.success(menuService.deleteMenuById(menuId));
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @ApiOperation(value = "获取路由信息")
    @GetMapping("getRouters")
    public JsonResult getRouters() {
        Long userId = SecurityUtils.getLoginUser().getUserid();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return JsonResult.success(menuService.buildMenus(menus));
    }

    @PostMapping("importData")
    public void importData(@RequestBody HashMap<String, List<SysMenuData>> sysMenuData) {
        List<SysMenuData> list = sysMenuData.get("sysMenuData");
        menuService.menuDataImport(list);
    }

    @PostMapping("importBtn")
    public void importBtn(@RequestBody HashMap<String, HashMap<String, String>> sysBtnData) {
        menuService.menuBtnImport(sysBtnData.get("sysBtnData"));
    }

    /**
     * 查询角色权限
     * @param userId
     * @return
     */
    @GetMapping("selectPerms/{userId}")
    public JsonResult<List<String>> selectPerms(@PathVariable("userId") Long userId){
        return JsonResult.success(menuService.selectPerms(userId));
    }
}
